import uuid
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Text, JSON, UniqueConstraint, Boolean
from sqlalchemy.orm import relationship, remote, backref
from datetime import datetime
from .database import Base

def generate_uuid(prefix: str) -> str:
    """生成带前缀的UUID"""
    return f"{prefix}_{uuid.uuid4().hex}"

class User(Base):
    __tablename__ = "users"
    
    id = Column(String(50), primary_key=True, index=True, default=lambda: generate_uuid("u"))
    username = Column(String(50), unique=True, index=True)
    password = Column(String(128))  # 修改为128长度，足够存储bcrypt哈希值
    profile_image = Column(String(200), nullable=True)  # 头像URL
    created_at = Column(DateTime, default=datetime.utcnow)
    gender = Column(Integer, default=2)  # 直接使用整数值
    bio = Column(Text, nullable=True)
    is_admin = Column(Integer, default=0)  # 0普通用户 1管理员
    
    # 关系
    avatar_id = Column(String(50), ForeignKey("avatars.id"), unique=True, nullable=True)
    # 一对一关系：一个用户对应一个化身
    avatar_entity = relationship(
        "Avatar",
        uselist=False,  # 一对一关系
        back_populates="user",
        foreign_keys=[avatar_id]
    )
    posts = relationship("Post", back_populates="author")
    comments = relationship("Comment", back_populates="author")
    
    # 好友关系(多对多)
    friends = relationship(
        "User",
        secondary="friendships",
        primaryjoin="User.id==Friendship.user_id",
        secondaryjoin="User.id==Friendship.friend_id",
        backref="friend_of"
    )

class Avatar(Base):
    __tablename__ = "avatars"
    
    id = Column(String(50), primary_key=True, index=True, default=lambda: generate_uuid("a"))
    prompt_settings = Column(JSON)  # 人设提示词
    appearance_image = Column(String(200))  # 外观形象URL
    voice_sample = Column(String(200))  # 声音采样URL
    video_sample = Column(String(200), nullable=True)  # 视频采样URL
    avatar_likes_count = Column(Integer, default=0)  # 改名：likes_count -> avatar_likes_count
    
    # 关系
    user_id = Column(String(50), ForeignKey("users.id"), unique=True)
    # 一对一关系：一个化身对应一个用户
    user = relationship(
        "User",
        uselist=False,  # 一对一关系
        back_populates="avatar_entity",
        foreign_keys="[User.avatar_id]",
        remote_side=[id]  # 指定远程端
    )

class Post(Base):
    __tablename__ = "posts"
    
    id = Column(String(50), primary_key=True, index=True, default=lambda: generate_uuid("p"))
    title = Column(String(100))
    content = Column(Text)
    created_at = Column(DateTime, default=datetime.utcnow)
    
    # 关系
    author_id = Column(String(50), ForeignKey("users.id"))
    author = relationship("User", back_populates="posts")
    comments = relationship("Comment", back_populates="post")
    
    # 点赞关系
    likes = relationship("PostLike", backref="post")
    post_likes_count = Column(Integer, default=0)  # 改名：likes_count -> post_likes_count

class Comment(Base):
    __tablename__ = "comments"
    
    id = Column(String(50), primary_key=True, index=True, default=lambda: generate_uuid("c"))
    content = Column(Text)
    created_at = Column(DateTime, default=datetime.utcnow)
    
    # 关系
    post_id = Column(String(50), ForeignKey("posts.id"))
    author_id = Column(String(50), ForeignKey("users.id"))
    parent_id = Column(String(50), ForeignKey("comments.id"), nullable=True)  # 父评论ID
    
    post = relationship("Post", back_populates="comments")
    author = relationship("User", back_populates="comments")
    # 添加父子评论关系
    replies = relationship("Comment", 
        backref=backref("parent", remote_side=[id]),
        cascade="all, delete-orphan"
    )

class Friendship(Base):
    __tablename__ = "friendships"
    
    id = Column(String(50), primary_key=True, index=True, default=lambda: generate_uuid("f"))
    user_id = Column(String(50), ForeignKey("users.id"))
    friend_id = Column(String(50), ForeignKey("users.id"))
    created_at = Column(DateTime, default=datetime.utcnow)

class FriendRequest(Base):
    __tablename__ = "friend_requests"
    
    friend_req_id = Column(String(50), primary_key=True, index=True, default=lambda: generate_uuid("fr"))
    from_user_id = Column(String(50), ForeignKey("users.id"))
    to_user_id = Column(String(50), ForeignKey("users.id"))
    status = Column(String(20), default="pending")
    created_at = Column(DateTime, default=datetime.utcnow)
    
    # 关系
    from_user = relationship("User", foreign_keys=[from_user_id])
    to_user = relationship("User", foreign_keys=[to_user_id])

class PostLike(Base):
    __tablename__ = "post_likes"
    
    id = Column(String(50), primary_key=True, index=True, default=lambda: generate_uuid("pl"))
    post_id = Column(String(50), ForeignKey("posts.id"))
    user_id = Column(String(50), ForeignKey("users.id"))
    created_at = Column(DateTime, default=datetime.utcnow)

class ChatMessage(Base):
    """聊天消息基类"""
    __tablename__ = "chat_messages"
    
    id = Column(String(50), primary_key=True, index=True, default=lambda: generate_uuid("m"))
    content = Column(Text)
    message_type = Column(String(20))  # friend_chat 或 avatar_chat
    created_at = Column(DateTime, default=datetime.utcnow)
    session_id = Column(String(50), ForeignKey("chat_sessions.id"))  # 添加session_id
    
    # 关系
    session = relationship("ChatSession", back_populates="messages")  # 添加关系
    
    __mapper_args__ = {
        'polymorphic_identity': 'chat_message',
        'polymorphic_on': message_type
    }

class FriendChatMessage(ChatMessage):
    """好友聊天消息"""
    __tablename__ = "friend_chat_messages"
    
    id = Column(String(50), ForeignKey('chat_messages.id'), primary_key=True)
    from_user_id = Column(String(50), ForeignKey("users.id"))
    to_user_id = Column(String(50), ForeignKey("users.id"))
    is_read = Column(Boolean, default=False)  # 是否已读
    
    # 关系
    from_user = relationship("User", foreign_keys=[from_user_id])
    to_user = relationship("User", foreign_keys=[to_user_id])
    
    __mapper_args__ = {
        'polymorphic_identity': 'friend_chat'
    }

class AvatarChatMessage(ChatMessage):
    """用户与化身聊天消息"""
    __tablename__ = "avatar_chat_messages"
    
    id = Column(String(50), ForeignKey('chat_messages.id'), primary_key=True)
    user_id = Column(String(50), ForeignKey("users.id"))
    avatar_id = Column(String(50), ForeignKey("avatars.id"))
    is_from_user = Column(Boolean)
    
    # 关系
    user = relationship("User")
    avatar = relationship("Avatar")
    
    __mapper_args__ = {
        'polymorphic_identity': 'avatar_chat'
    }

class ChatSession(Base):
    """聊天会话"""
    __tablename__ = "chat_sessions"
    
    id = Column(String(50), primary_key=True, index=True, default=lambda: generate_uuid("s"))
    session_type = Column(String(20))  # friend_session 或 avatar_session
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 添加关系
    messages = relationship("ChatMessage", back_populates="session")
    
    __mapper_args__ = {
        'polymorphic_identity': 'chat_session',
        'polymorphic_on': session_type
    }

class FriendChatSession(ChatSession):
    """好友聊天会话"""
    __tablename__ = "friend_chat_sessions"
    
    id = Column(String(50), ForeignKey('chat_sessions.id'), primary_key=True)
    user1_id = Column(String(50), ForeignKey("users.id"))
    user2_id = Column(String(50), ForeignKey("users.id"))
    user1_unread_count = Column(Integer, default=0)
    user2_unread_count = Column(Integer, default=0)
    
    # 关系
    user1 = relationship("User", foreign_keys=[user1_id])
    user2 = relationship("User", foreign_keys=[user2_id])
    
    __mapper_args__ = {
        'polymorphic_identity': 'friend_session'
    }

class AvatarChatSession(ChatSession):
    """用户与化身聊天会话"""
    __tablename__ = "avatar_chat_sessions"
    
    id = Column(String(50), ForeignKey('chat_sessions.id'), primary_key=True)
    user_id = Column(String(50), ForeignKey("users.id"))
    avatar_id = Column(String(50), ForeignKey("avatars.id"))
    
    # 关系
    user = relationship("User")
    avatar = relationship("Avatar")
    
    __mapper_args__ = {
        'polymorphic_identity': 'avatar_session'
    } 